﻿using System;
using System.Security;
using System.Security.Principal;
using System.Web.Security;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using CMS.Web.Data;

namespace CMS.Web.Engine
{
    [Widget(Guid = "67f4a8a0-d350-4243-af08-32aa25a21e8a", 
        Name = "Аутентификация/Авторизация", 
        Category = "Безопасность",
        PartialViewName = "~/Widgets/Login/Default.cshtml",         
        Description = "Виджет для аутентификации/авторизации пользователя.")]
    public class WidgetLogin : WidgetBase
    {
        public WidgetLogin()
        {
            this.Settings = new WidgetSettings(); 
        }
        public override void Initialize(string serializedSettings, IEnumerable<string> ids)
        {
            if (!serializedSettings.IsEmpty())
                this.Settings = Json.Deserialize<WidgetSettings>(serializedSettings);

            FormsIdentity identity = (HttpContext.Current.User.Identity as FormsIdentity);

            this.Model = new WidgetModelLogin
            {                
                Login = !identity.IsNull() ? identity.Name : string.Empty,
                IsAuthenticated = !identity.IsNull(),
                Widget = this.ID               
            };           
        }

        public override void ProcessPost()
        {
            WidgetModelLogin model = (WidgetModelLogin)Model;
            try
            {
                IUsersRepository users = IoCContainer.Current.Resolve<IUsersRepository>();
                if (!model.IsAuthenticated)
                {
                    IUserEntity user = users.Login(model.Login, model.Password);                    
                    model.DisplayName = user.DisplayName;
                }
                else
                    users.Logoff();

                model.IsAuthenticated = !model.IsAuthenticated;
            }
            catch (Exception exc)
            {
                model.Errors.Add(exc); 
            }
        }
    }

    public class WidgetModelLogin : WidgetModel
    {
        public string Login { get; set; }
        public string Password { get; set; }
        public string DisplayName { get; set; }
        public bool IsAuthenticated { get; set; }
    }
}